package com.topisv.tms.utils.http;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.entity.stock.instorage.pre.PreInBill;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.utils.enums.PYOrderType;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.io.ReaderXML;
import com.topisv.tms.utils.mail.MailSenderInfo;
import com.topisv.tms.utils.mail.SimpleMailSender;
import com.topisv.tms.utils.vo.PreInstorageVo;

/**
 * 预约入库邮件发送
 *  Date          Author       Version       Description
 * ----------------------------------------------------------
 *  2014-12-22      CC            1.0           Create
 */
@Component
public class PreBillMailSender implements Runnable {
	private Logger log = LoggerFactory.getLogger(PreBillMailSender.class);
	@Autowired
	private AccountService accountService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;

	@Override
	public void run() {
		while (true) {
			try {
				PreInstorageVo preInstorageVo = SynchroShippedBatchQueue.takePreBillMail();
				if (preInstorageVo != null) {
					//sendMail(preInstorageVo);
				}
			} catch (Exception e) {
				log.error("PreBillMailSender case some error.", e);
			}
		}
	}

	private void sendMail(PreInstorageVo preInstorageVo) {
		MailSenderInfo mailInfo = buildMailInfo(getTitle(preInstorageVo), buildMailContent(preInstorageVo), queryToAddress(preInstorageVo));
		boolean rs = SimpleMailSender.sendHtmlMail(mailInfo);
		log.info("{} send mail {}", preInstorageVo.getInstorageBillPre().getBillCode(), rs);
	}

	private String getTitle(PreInstorageVo preInstorageVo) {
		String billType = preInstorageVo.getInstorageBillPre().getBillType();
		String areaGroupCode = preInstorageVo.getInstorageBillPre().getInwarehouseCode();
		AreaGroup areaGroup = areaGroupService.findByGroupCode(areaGroupCode);
		String groupName = areaGroup == null? "" :areaGroup.getGroupName();
		if (PYOrderType.PRE_ORDER.getType().equals(billType)) {
			return new StringBuilder().append("【重要】").append(groupName).append("有新的入库预约单申请.").toString();
		} else if (PYOrderType.RETURN_ORDER.getType().equals(billType)) {
			return new StringBuilder().append("【重要】").append(groupName).append("有新的退货预约单申请.").toString();
		} else {
			return new StringBuilder().append("【重要】").append(groupName).append("有新的入库预约单申请.").toString();
		}
	}

	private String queryToAddress(PreInstorageVo preInstorageVo) {
		// 发给有仓库管理员角色的员工
		List<Userrole> rs = accountService.findByRoleName(StatusEnums.user_type_paiu.getStatus(), Arrays.asList("仓库管理员","退货管理"), preInstorageVo.getInstorageBillPre().getInwarehouseCode());
		StringBuilder sb = new StringBuilder();
		for (Userrole userrole : rs) {
			String mail = userrole.getUser().getMail();
			if (!StringUtils.isBlank(mail)) {
				sb.append(mail).append(",");
			}
		}
		return sb.length() == 0 ? sb.toString() : sb.deleteCharAt(sb.length() - 1).toString();
	}

	private String buildMailContent(PreInstorageVo preInstorageVo) {
		InstorageBillPre billPre = preInstorageVo.getInstorageBillPre();
		Element root = ReaderXML.read("/template/preBill.xml");
		Element bodyElement = root.element("html").element("body");
		// 处理1:
		Element spanElement = bodyElement.element("span");
		String preSendTime = "";
		if (billPre.getPreSendTm() != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			preSendTime = sdf.format(billPre.getPreSendTm());
		}
		Customers customer = customersService.findByCustomerCode(billPre.getCustomerCode());
		List<PreInBill> preInBills = billPre.getPreInBills();
		String inBillCode = preInBills != null && !preInBills.isEmpty() ? preInBills.get(0).getInBillCode() : null;
		spanElement.setText(MessageFormat.format(spanElement.getText(), customer.getCustomerName(), inBillCode, billPre.getGoodsNum(), preSendTime));
		return HtmlUtils.htmlUnescape(root.element("html").asXML());
	}

	private MailSenderInfo buildMailInfo(String title, String content, String toAddress) {
		MailSenderInfo mailInfo = new MailSenderInfo();

		mailInfo.setMailServerHost("smtp.exmail.qq.com");
		mailInfo.setMailServerPort("587");
		mailInfo.setValidate(true);

		mailInfo.setUserName("operation@paiu.com.cn");
		mailInfo.setPassword("paiu2014");

		mailInfo.setFromAddress("operation@paiu.com.cn");
		mailInfo.setToAddress(toAddress.split(","));
		mailInfo.setCcAddress(new String[] { "zhangyuxuan@paiu.com.cn", "zhangpei@paiu.com.cn"});
//		 mailInfo.setToAddress(new String[] { "caocao@paiu.com.cn" });
//		 mailInfo.setCcAddress(new String[] { "caocao@paiu.com.cn" });
		mailInfo.setSubject(title);
		mailInfo.setContent(content);
		return mailInfo;
	}
}
